import {
  BrowserRouter as Router,
  Routes,
  Route,
  Link,
  useSearchParams,
} from "react-router-dom";

import { Toast } from "antd-mobile";

import logo from "./logo.svg";
import "./App.css";
import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom/client";
import { unstable_batchedUpdates } from "react-dom";

// 添加polyfill
ReactDOM.__unstable_batchedUpdates = unstable_batchedUpdates;
function Home() {
  const [data, setData] = useState([]);
  const [monthSumPrice, setMonthSumPrice] = useState(0);

  const [searchParams] = useSearchParams();
  const token = searchParams.get("token");
  useEffect(() => {
    fetchFn();
  }, []);
  const fetchFn = () => {
    fetch("http://47.96.71.171:1000/app/api/user/getLcConfigList/v1_0_0", {
      headers: {
        Accept: "application/json",
        stewed_fruit_toKen:
          token ||
          "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwaG9uZSI6IjE3MzU3NTY5MjA1IiwidXVpZCI6OTMxMDMxfQ.nM_4s6-9VtdxJar1qUmL48GraaP9pmMcLBNlQ-vp8RM",
      },
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        return response.json();
      })
      .then((data) => {
        data.data?.configList?.forEach((element) => {
          if (element.accumulatedRecharge > data.data.monthSumPrice) {
            element.status = "未达标";
          } else if (element.lqFlag) {
            element.status = "已领取";
          } else {
            element.status = "立刻领取";
          }
        });
        setData(data.data.configList);
        setMonthSumPrice(data?.data?.monthSumPrice);
        console.log(data.data.configList, "----");
      })
      .catch((error) => console.error("Error:", error));
  };
  const Collect = (item) => {
    console.log(item, "----");
    if (item.goldNum && item.personalDressingId && item.status === "立刻领取") {
      fetch("http://47.96.71.171:1000/app/api/user/lqlcjl/v1_0_0", {
        method: "POST", // 指定请求方法
        headers: {
          "Content-Type": "application/json", // 设置请求头为 JSON 格式:ml-citation{ref="2,5" data="citationList"}
          stewed_fruit_toKen:
            token ||
            "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwaG9uZSI6IjE3MzU3NTY5MjA1IiwidXVpZCI6NTA2MDcyfQ.rmmdM3fQbMlBTx7n0-GHYOfjZB-MQqaeRmimSALHEr4",
        },
        body: JSON.stringify({ configId: item.configId }), // 将数据转换为 JSON 字符串
      })
        .then((response) => {
          if (!response.ok) {
            throw new Error("请求失败");
          }
          return response.json();
        })
        .then((data) => {
          if (data.code !== 200) {
            Toast.show({
              content: data.msg,
              duration: 2000,
            });
            return;
          }
          Toast.show({
            content: "领取成功",
            duration: 2000,
          });
          fetchFn(); // 重新获取数据更新状态
        });
    }
  };
  return (
    <div style={{ width: "100%", backgroundColor: "#200236" }}>
      {data.map((item, index) => {
        return (
          <div
            key={item.id}
            style={{
              backgroundImage: `url(${item.backgroundImg})`,
              backgroundSize: "cover",
              backgroundPosition: "center",
              backgroundRepeat: "no-repeat",
              width: "100vw",
              height: "240px", // 根据需要调整高度
              display: "block",
              position: "relative",
              objectFit: "cover",
            }}
            onClick={() => Collect(item)}
          >
            {index === 0 && (
              <div
                style={{
                  position: "absolute",
                  bottom: "0",
                  left: "50%", // 新增
                  transform: "translateX(-50%)", // 新增
                  padding: "6px 10px",
                  color: "#fff",
                  cursor: "pointer",
                  fontWeight: "bold",
                  fontSize: "18px",
                  width: "100%",
                }}
              >
                本月累计充值：{monthSumPrice}元
              </div>
            )}
            {item.goldNum && item.personalDressingId ? (
              <div
                style={{
                  position: "absolute",
                  bottom: "20px",
                  left: "50%", // 新增
                  transform: "translateX(-50%)", // 新增
                  padding: "5px 10px",
                  borderRadius: "5px",
                  backgroundColor:
                    item.status === "未达标"
                      ? "orange"
                      : item.status === "已领取"
                      ? "gray"
                      : "green",
                  color: "#fff",
                  cursor: "pointer",
                  fontSize: "16px",
                }}
              >
                {!!item.status && item.status}
              </div>
            ) : null}
          </div>
        );
      })}
    </div>
  );
}

function About() {
  return <h2>About Page</h2>;
}

function App() {
  // useEffect(() => {
  //   fetch("/api/login", {
  //     headers: {
  //       Accept: "application/json",
  //     },
  //   })
  //     .then((response) => {
  //       if (!response.ok) {
  //         throw new Error("Network response was not ok");
  //       }
  //       return response.json();
  //     })
  //     .then((data) => setData(data))
  //     .catch((error) => console.error("Error:", error));
  // }, []);

  return (
    <Router>
      <div className="App">
        <header className="App-header">
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/about" element={<About />} />
          </Routes>
        </header>
      </div>
    </Router>
  );
}

export default App;
